<?php

class CSql {

    function insert($arr, $table) {
        $sql = "insert into $table (";
        $flag = 0;
        foreach ($arr as $k => $v) {
            $sql .= ( $flag == 0 ? "`" : ", `") . $k . "`";
            $flag = 1;
        }
        $sql .= ") values(";
        $flag = 0;
        foreach ($arr as $k => $v) {
            $sql .= ( $flag == 0 ? "'" : ", '") . mysql_escape_string($v) . "'";
            $flag = 1;
        }
        $sql .= ")";
        return $sql;
    }

    function replace($arr, $table) {
        $sql = "replace into $table (";
        $flag = 0;
        foreach ($arr as $k => $v) {
            $sql .= ( $flag == 0 ? "" : ", ") . $k;
            $flag = 1;
        }
        $sql .= ") values(";
        $flag = 0;
        foreach ($arr as $k => $v) {
            $sql .= ( $flag == 0 ? "'" : ", '") . mysql_escape_string($v) . "'";
            $flag = 1;
        }
        $sql .= ")";

        return $sql;
    }

    function update($arr, $table, $where) {
        $sql = "update $table set ";
        $flag = 0;
        foreach ($arr as $k => $v) {
            $k = str_replace("`", "", $k);
            $sql .= ( $flag == 0 ? "`" : ", `") . $k . "` = '" . mysql_escape_string($v) . "'";
            $flag = 1;
        }
        $sql .= " " . $where;

        return $sql;
    }

    function updateEx($arr, $change, $table, $where) {
        $sql = "update $table set ";
        $flag = 0;
        foreach ($arr as $k => $v) {
            $sql .= ( $flag == 0 ? "" : ", ") . $k . " = '" . mysql_escape_string($v) . "'";
            $flag = 1;
        }
        foreach ($change as $k => $v) {
            if (is_numeric($v)) {
                $sql .= sprintf("%s %s=%s%s%s", ($flag == 0 ? "" : ","), $k, $k, ($v >= 0 ? "+" : " "), $v);
                $flag = 1;
            } else {
                $sql .= sprintf("%s %s=CONCAT(%s,'%s')", ($flag == 0 ? "" : ","), $k, $k, mysql_escape_string($v));
                $flag = 1;
            }
        }
        $sql .= " " . $where;

        return $sql;
    }

}

?>